<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="isEdit ? '编辑物品' : '新增物品'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item required label="活动名称" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入活动名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="Banner图片" prop="imageUrl">
        <div class="image-preview">
          <Upload
            class="upload"
            :showFileList="false"
            :ossDir="OSS_DIR.BANNER"
            accept=".jpg,.jpeg,.png"
            buttonText="上传Banner"
            @upload-success="handleUploadSuccess"
          />

          <img
            :src="formData.imageUrl"
            width="180"
            height="60"
            class="preview-avatar"
          />
        </div>
        <div class="image-preview">
          <Upload
            class="upload"
            :showFileList="false"
            :ossDir="OSS_DIR.BANNER"
            accept=".jpg,.jpeg,.png"
            buttonText="上传阿语Banner"
            @upload-success="handleUploadSuccessAnimation"
          />

          <img
            :src="formData.arImageUrl"
            width="180"
            height="60"
            class="preview-avatar"
          />
        </div>
      </el-form-item>

      <el-form-item label="打开方式" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择打开方式"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="category in typeOptions"
            :key="category.key"
            :label="category.desc"
            :value="category.key"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跳转方式" prop="subType">
        <el-select
          v-model="formData.subType"
          placeholder="请选择跳转方式"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="category in subtypeOptions"
            :key="category.key"
            :label="category.desc"
            :value="category.key"
          />
        </el-select>
      </el-form-item>

      <el-divider v-if="formData.type == 1" content-position="left"
        >外部浏览器链接</el-divider
      >

      <el-form-item
        v-if="formData.type == 1"
        label="安卓链接"
        prop="params.android"
      >
        <el-input
          v-model="formData.params.android"
          placeholder="请输入安卓链接"
          clearable
        />
      </el-form-item>

      <el-form-item v-if="formData.type == 1" label="Ios链接" prop="params.ios">
        <el-input
          v-model="formData.params.ios"
          placeholder="请输入Ios链接"
          clearable
        />
      </el-form-item>

      <el-form-item v-if="formData.type == 1" label="H5链接" prop="params.h5">
        <el-input
          v-model="formData.params.h5"
          placeholder="请输入H5链接"
          clearable
        />
      </el-form-item>

      <el-divider content-position="left">其他配置</el-divider>

      <el-form-item label="时间范围">
        <el-date-picker
          ref="datePickerRef"
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 400px"
        />
      </el-form-item>

      <el-form-item label="上架状态" prop="enable">
        <el-switch
          v-model="formData.enable"
          active-text="已上架"
          inactive-text="未上架"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import {
  ElDatePicker,
  ElMessage,
  type FormInstance,
  type FormRules,
} from "element-plus";
import Upload from "@/components/upload/OssUpload.vue";
import { OSS_DIR } from "@/api/oss";
import {
  getGoodCategoriesApi,
  type GoodsCategoryRecord,
  updateGoodApi,
} from "@/api/good";
import { BannerInfo, createBannerApi, updateBannerApi } from "@/api/banner";

interface Props {
  modelValue: boolean;
  goodData?: BannerInfo | null;
  isEdit?: boolean;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "submit"): void;
}

const typeOptions = [
  { key: 0, desc: "h5 url" },
  { key: 1, desc: "app内页面" },
];

const subtypeOptions = [
  { key: 0, desc: "端内Webview 打开" },
  { key: 1, desc: "外部浏览器打开" },
];

const props = withDefaults(defineProps<Props>(), {
  goodData: null,
  isEdit: false,
});

const emit = defineEmits<Emits>();

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const formRef = ref<FormInstance>();
const categoryOptions = ref<GoodsCategoryRecord[]>([]);

const datePickerRef = ref<InstanceType<typeof ElDatePicker> | null>(null);
const dateRange = ref<[string, string] | null>(null);

// 表单数据
const formData = reactive<BannerInfo>({
  id: "",
  createUser: "", // 创建者
  type: null, // banner类型，0: h5 url, 1: app内页面
  url: "", // 跳转链接，h5url 'https://www.baidu.com' 或者 端内页面 '/myWallet'
  subType: null, // 子类型，当type为0的时候,需要区分 0: 端内webview 打开, 1:外部浏览器打开
  title: "", // 标题
  imageUrl: "", // 图片链接
  arImageUrl: "", // 阿拉伯语图片链接
  // 参数配置，参数, 如有, 如果 type 为 0 时, 直接拼接在 url 后面,不使用该参数; 如果 type 为 1 时, 需要{'key':"value"}
  params: {
    android: "",
    ios: "",
    h5: "",
  },
  enable: false, // 是否启用
  startTime: null, // 开始时间
  endTime: null, // 结束时间
});

// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择物品类型", trigger: "change" }],
  subType: [{ required: true, message: "请选择物品类型", trigger: "change" }],

  "params.android": [
    { required: true, message: "请输入阿语名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  "params.ios": [
    { required: true, message: "请输入阿语名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  "params.h5": [
    { required: true, message: "请输入阿语名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  previewImageUrl: [
    { required: true, message: "请输入预览图片URL", trigger: "blur" },
    { type: "url", message: "请输入正确的URL格式", trigger: "blur" },
  ],
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      loadCategories();
      if (props.isEdit && props.goodData) {
        initFormData();
      } else {
        resetFormData();
      }
    }
  }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 加载物品分类
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi();
    categoryOptions.value = response.data;
    console.log("物品分类:", response.data);
  } catch (error) {
    console.error("加载物品分类失败:", error);
  }
};

// 初始化表单数据（编辑模式）
const initFormData = () => {
  dateRange.value = [null, null];

  if (!props.goodData) return;

  Object.assign(formData, {
    id: props.goodData.id,
    type: props.goodData.type, // banner类型，0: h5 url, 1: app内页面
    url: props.goodData.url, // 跳转链接，h5url 'https://www.baidu.com' 或者 端内页面 '/myWallet'
    subType: props.goodData.subType, // 子类型，当type为0的时候,需要区分 0: 端内webview 打开, 1:外部浏览器打开
    title: props.goodData.title, // 标题
    imageUrl: props.goodData.imageUrl, // 图片链接
    arImageUrl: props.goodData.arImageUrl, // 阿拉伯语图片链接
    // 参数配置，参数, 如有, 如果 type 为 0 时, 直接拼接在 url 后面,不使用该参数; 如果 type 为 1 时, 需要{'key':"value"}
    params: props.goodData.params,
    enable: props.goodData.enable,
  });
  dateRange.value = [
    props.goodData.startTime ? String(props.goodData.startTime) : null,
    props.goodData.endTime ? String(props.goodData.endTime) : null,
  ];
};

// 重置表单数据（新增模式）
const resetFormData = () => {
  Object.assign(formData, {
    id: "",
    createUser: "", // 创建者
    type: "", // banner类型，0: h5 url, 1: app内页面
    url: "", // 跳转链接，h5url 'https://www.baidu.com' 或者 端内页面 '/myWallet'
    subType: "", // 子类型，当type为0的时候,需要区分 0: 端内webview 打开, 1:外部浏览器打开
    title: "", // 标题
    imageUrl: "", // 图片链接
    arImageUrl: "", // 阿拉伯语图片链接
    // 参数配置，参数, 如有, 如果 type 为 0 时, 直接拼接在 url 后面,不使用该参数; 如果 type 为 1 时, 需要{'key':"value"}
    params: {
      android: "",
      ios: "",
      h5: "",
    },
    enable: false, // 是否启用
    startTime: null, // 开始时间
    endTime: null, // 结束时间
  });
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
};

// 上传成功，保存到表单变量
const handleUploadSuccess = (file: any) => {
  formData.imageUrl = file;
};
const handleUploadSuccessAnimation = (file: any) => {
  formData.arImageUrl = file;
};

// 转换为UTC时间
const convertToUTC = (localTime: string) => {
  if (!localTime) return "";
  const date = new Date(localTime);
  return date.toISOString();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    loading.value = true;

    // 更新 name.text 字段

    // 如果是编辑模式，需要包含ID
    const submitData = props.isEdit
      ? {
          ...formData,
          id: props.goodData?.id,
          startTime: convertToUTC(dateRange.value[0]),
          endTime: convertToUTC(dateRange.value[1]),
        }
      : {
          ...formData,
          startTime: convertToUTC(dateRange.value[0]),
          endTime: convertToUTC(dateRange.value[1]),
        };

    // if (props.isEdit) {
    //   await updateGoodApi(submitData);
    // } else {
    //   await createBannerApi(submitData);
    // }

    if (!props.isEdit) {
      delete submitData.id;
    }

    console.log("submitData", submitData);

    if (props.isEdit) {
      await updateBannerApi(submitData);
    } else {
      await createBannerApi(submitData);
    }

    // await createBannerApi(submitData);

    ElMessage.success(props.isEdit ? "更新成功" : "创建成功");
    emit("submit");
    handleClose();
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      return;
    }
    console.error("提交失败:", error);
    ElMessage.error(props.isEdit ? "更新失败" : "创建失败");
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  open: () => {
    visible.value = true;
  },
  close: handleClose,
});
</script>

<style scoped lang="less">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.image-preview {
  margin-top: 10px;

  .preview-avatar {
    border: 1px solid #e4e7ed;
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.1);
    }
  }
}

.upload {
  margin-bottom: 10px;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409eff;
}
</style>
